<template>
	<view class="warp">
		<uni-data-select v-model="value" :localdata="range" placeholder="选择省" @change="change"></uni-data-select>
		<uni-data-select v-if="index>0" v-model="sValue" placeholder="选择市" :localdata="srange"
			@change="schange"></uni-data-select>
		<uni-data-select v-if="index>1" v-model="xValue" placeholder="选择县" :localdata="xrange"
			@change="xchange"></uni-data-select>
	</view>
</template>

<script>
	const db = uniCloud.database();

	export default {
		name: "select-city",
		props: {
			modleValue: [String, Array]
		},
		data() {
			return {
				value: '', //省
				sValue: '', //市
				xValue: '', //县
				index: 0,
				range: [],
				srange: [],
				xrange: [],
				code: '',
				scode: '',
				xcode: ''
			};
		},
		mounted() {
			this.load()
		},
		methods: {
			load(code) {
				try{
					let where = "parent_code=='' || parent_code==null"
					if (code) {
						where = `parent_code=='${code}'`
					}
					db.collection('opendb-city-china').where(where).field("name as text,code as value").get().then(res => {
						if (this.index == 0) {
							this.range = res.result.data
						}
						if (this.index == 1) {
							this.srange = res.result.data
						}
						if (this.index == 2) {
							this.xrange = res.result.data
						}
					})
				}catch(e){
					console.log("select-city===>>>catch",e);
				}
			},
			change(e) {
				// console.log("e:", e);
				if (e) {
					this.index = 1
					this.load(e)
					this.code = e
				} else {
					this.index = 0
				}
				this.$emit("update:modelValue", e)
			},
			schange(e) {
				// console.log("e:", e);
				this.scode = e
				this.load(e)
				if (e) {
					this.index = 2
					this.$emit("update:modelValue", e)
				} else {
					this.index = 0
					this.$emit("update:modelValue", this.code)
				}
			},
			xchange(e) {
				// console.log("e:", e);
				this.xcode = e
				if (e) {
					this.$emit("update:modelValue", e)
				} else {
					this.index = 1
					this.$emit("update:modelValue", this.scode)
				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	.warp {
		display: flex;
	}
</style>